package pers.ree.demo.designpattern.singleton;

public class SynMethodSingleton {

    private static SynMethodSingleton instance;

    // 不能用直接用字符串常量（如"lock1"）当锁，否则容易导致意外的死锁
    // 此处貌似用Object对象作锁比用String更好，参见Thread.blockerLock
    private static final String lock1 = new String("lock1");
    private static final String lock2 = new String("lock2");


    private SynMethodSingleton() {

    }


    public static synchronized SynMethodSingleton getInstance() {
        if (instance == null) {
            instance = new SynMethodSingleton();
        }

        return instance;
    }

    /****** 以下是在方法上加锁的变种，只有一个方法时效果与在方法上加锁等同，但是有多个方法时，不同方法可以用不同的锁，效率会高些 ***/
    public static SynMethodSingleton getInstance2() {
        synchronized (lock1) {
            if (instance == null) {
                instance = new SynMethodSingleton();
            }
        }

        return instance;
    }

    public static SynMethodSingleton getInstance3() {
        synchronized (lock2) {
            if (instance == null) {
                instance = new SynMethodSingleton();
            }
        }

        return instance;
    }


    public static void main(String[] args) {

    }
}
